package com.stu.wgt.test.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.stu.wgt.test.bean.Merchant;
import com.stu.wgt.test.result.R;
import com.stu.wgt.test.result.ResultCodeEnum;
import com.stu.wgt.test.service.MerchantService;
import com.stu.wgt.test.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wgt
 * @since 2024-02-05
 */
@RestController
@RequestMapping("/merchant")
public class MerchantController {
    @Autowired
    MerchantService merchantService;

    // 查询所有商家
    @RequestMapping(value = "/merchant", method = RequestMethod.GET)
    public R selectAllMerchant() {
        try {
            List<Merchant> merchants = merchantService.selectAllMerchant();
            return R.ok().data("merchants", merchants);
        } catch (Exception e) {
            return R.error().data("msg", "查询失败");
        }
    }

    // 根据ID查找商家
    @RequestMapping(value = "/selectById/{id}", method = RequestMethod.GET)
    public R selectByID(@PathVariable int id) {
        if (id <= 0) {
            return R.error().data("msg", "请输入正确的ID");
        }
        try {
            List<Merchant> merchantList = merchantService.selectById(id);
            return R.ok().data("merchant", merchantList);
        } catch (Exception e) {
            return R.error().data("msg", "没有找到该商家");
        }
    }

    //  分页查询
    @GetMapping("/search")
    public R searchUsers(@RequestParam("query") String query,
                         @RequestParam("pagenum") int pageNum,
                         @RequestParam("pagesize") int pageSize) {
        // 根据查询关键字、当前页数和每页显示的数据条数进行查询操作
        try {
            IPage<Merchant> merchantIPage = merchantService.searchMerchant(query, pageNum, pageSize);
            return R.ok().data("merchant", merchantIPage.getRecords()).data("total", merchantIPage.getTotal());
        } catch (Exception e) {
            return R.error().data("msg", "查询失败");
        }
    }

    // 添加新的商家
    @RequestMapping(value = "/addMerchant", method = RequestMethod.POST)
    public R addMerchant(@RequestBody Merchant merchant) {
        // 使用 md5 更新密码
        String md5Password = DigestUtils.md5DigestAsHex(merchant.getPassword().getBytes());
        merchant.setPassword(md5Password);
        int result = merchantService.insert(merchant);
        if (result == 1) {
            return R.ok().data("msg", "添加成功");
        }
        return R.error().data("msg", "添加失败");
    }

    // 修改商家信息
    @RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
    public R updateMerchant(@PathVariable("id") Integer id, @RequestBody Merchant merchant) {
        System.out.println(merchant);
        merchant.setId(id);
        merchant.setPassword(DigestUtils.md5DigestAsHex(merchant.getPassword().getBytes()));
        System.out.println(merchant);
        int result = merchantService.update(merchant);
        if (result == 1) {
            return R.ok().data("msg", "修改成功");
        }
        return R.setResult(ResultCodeEnum.BAD_REQUEST);
    }

    // 删除商家
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public R deleteMerchant(@PathVariable int id) {
        int result = merchantService.delete(id);
        if (result == 1) {
            return R.ok().data("msg", "删除成功");
        }
        return R.error().data("msg", "删除失败");
    }

    // 商家登录
    @RequestMapping("/login")
    public R login(@RequestBody Merchant merchant) {
        System.out.println(merchant);
        // 使用 MD5 加密算法对密码进行加密
        String md5Password = DigestUtils.md5DigestAsHex(merchant.getPassword().getBytes());

        // 检查用户输入的手机号
        List<Merchant> merchant1;
        if (merchant.getPhone().matches("^1[3-9]\\d{9}$") && merchant.getPhone().length() > 10) {
            merchant1 = merchantService.selectByTelephone(merchant.getPhone());
        } else {
            return R.setResult(ResultCodeEnum.BAD_REQUEST).data("msg", "手机号输入错误");
        }
        if (merchant1.isEmpty()) {
            return R.setResult(ResultCodeEnum.NOT_FOUND).data("msg", "用户未注册，请前往注册");
        }
        System.out.println(md5Password + "\n" + merchant1.get(0).getPassword());
        if (!md5Password.equals(merchant1.get(0).getPassword())) {
            return R.setResult(ResultCodeEnum.BAD_REQUEST).data("msg", "用户密码输入错误");
        } else {
            String token = JwtUtil.createToken("merchant");
            return R.ok().data("token", token).data("member", merchant1);
        }
    }
}

